package com.homework8;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;

public class Server{
    public static void main(String[] args) throws IOException {
        Map<String,String> hashtable = new HashMap<>();
        BufferedReader fis = new BufferedReader(new InputStreamReader(new FileInputStream("C:\\Users\\admin\\Desktop\\login.txt")));
        String info;
        while(null != (info = fis.readLine())){
            String[] split = info.split("=");
            hashtable.put(split[0],split[1]);
        }
        fis.close();
        //接收数据
        ServerSocket serverSocket = new ServerSocket(8888);
        Socket socket = serverSocket.accept();
        InputStream is = socket.getInputStream();
        OutputStream os = socket.getOutputStream();
        byte[] bytes = new byte[1024];
        int len = is.read(bytes);
        info = new String(bytes,0,len);
        //分割字符串
        String[] split = info.split("=");
        //判断是否存在
        if(split.length!=2){
            os.write("格式不正确!".getBytes());
        }else if(hashtable.containsKey(split[0])){
            if(hashtable.get(split[0]).equals(split[1])){
                os.write("登陆成功!".getBytes());
            }else{
                os.write("密码错误!".getBytes());
            }
        }else{
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("C:\\Users\\admin\\Desktop\\login.txt",true)));
            bw.write(info);
            bw.newLine();
            bw.close();
            os.write("注册成功!".getBytes());
        }
        socket.close();
    }
}
